package com.hutu.utils;

import cn.hutool.json.JSONUtil;
import com.hutu.model.dto.question.QuestionContentDTO;
import com.hutu.model.entity.ScoringResult;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ScoringUtils {

    /**
     * 测评工具
     * @param choices
     * @param questionContentDTOList
     * @param scoringResults
     * @return
     */
    public static ScoringResult findBestScoreResult(List<String> choices, List<QuestionContentDTO> questionContentDTOList, List<ScoringResult> scoringResults) {
        // 定义一个统计选择了那些性格的map  [I,S, E,N,O]
        Map<String, Integer> scoreMap = new HashMap<>();
        // 遍历用户所选答案
        for (int i = 0; i < choices.size(); i++) {
            String choice = choices.get(i);
            // 如果用户未作答,则跳过该题
            if (choice != null) {
                QuestionContentDTO questionContentDTO = questionContentDTOList.get(i);
                QuestionContentDTO.Option option = questionContentDTO.getOptions().stream()
                        .filter(o -> o.getKey().equals(choice))
                        .findFirst()
                        .orElse(null);
                if (option != null) {
                    String result = option.getResult(); // 结果值
                    // 为所有包含此结果值的评分结果加1分
                    scoreMap.put(result, scoreMap.getOrDefault(result, 0) + 1);
                }
            }
        }
        ScoringResult bestResult = scoringResults.get(0);
        int maxScore = 0;
        // 遍历scoringResults,然后选出最优的结果集
        for (ScoringResult scoringResult : scoringResults) {
            String resultProp = scoringResult.getResultProp();
            // [I,S,T,J] 转成 list
            List<String> strings = JSONUtil.toList(resultProp, String.class);
            int sum = strings.stream().mapToInt(s -> scoreMap.getOrDefault(s, 0)).sum();
            if (sum > maxScore) {
                maxScore = sum;
                bestResult = scoringResult;
            }
        }
        return bestResult;
    }


    /**
     * 统计得分工具
     * @param choices
     * @param questionContentDTOList
     * @return
     */
    public static int findBestScore(List<String> choices, List<QuestionContentDTO> questionContentDTOList) {
        int score = 0;
        for (int i = 0; i < choices.size(); i++) {
            String choice = choices.get(i);
            // 如果用户未作答,则跳过该题
            if (choice != null) {
                QuestionContentDTO questionContentDTO = questionContentDTOList.get(i);
                QuestionContentDTO.Option option = questionContentDTO.getOptions().stream()
                        .filter(o -> o.getKey().equals(choice))
                        .findFirst()
                        .orElse(null);
                if (option != null) {
                    score += option.getScore();
                }
            }
        }
        return score;
    }
}
